package com.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * Copyright (c) 2023-2033 All Rights Reserved
 *
 * SqlSession工具类
 * TODO: 通过 Resource 读取配置文件，转为字节流
 *
 * @date: 2023/9/27
 */
public class SqlSessionUtils {

    /**
     * 通过Mybatis主配置文件创建SqlSession并返回
     * @return SqlSession
     */
    public static SqlSession getSqlSession() {
        SqlSession sqlSession = null;
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            sqlSession = sqlSessionFactory.openSession(true);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return sqlSession;
    }
}
